//
//  DHSubscription_BrandView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/6/8.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSubscription_BrandView.h"
#import "S2_Brand.h"
#import "DHHomeHotBrandsCell.h"
#import "UITableView+CCPIndexView.h"
#import "DHSubscription_BrandViewCell.h"
#import "DHS2_BrandViewController.h"

@interface DHSubscription_BrandView()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray *brandArray;
@property (strong, nonatomic) NSArray *hotArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation DHSubscription_BrandView

+ (DHSubscription_BrandView *)shareDHSubscription_BrandView{
    DHSubscription_BrandView *view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([DHSubscription_BrandView class]) owner:self options:nil] objectAtIndex:0];
    return view;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeHotBrandsCell" bundle:nil] forCellReuseIdentifier:kDHHomeHotBrandsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHSubscription_BrandViewCell" bundle:nil] forCellReuseIdentifier:kDHSubscription_BrandViewCell];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSArray *)brandArray{
    if (!_brandArray) {
        _brandArray = [NSArray array];
    }
    return _brandArray;
}

- (void)loadData{
    //热门品牌
    [[DHNetAPIClient shareDHNetAPIClient] request_brands_hotWithParams:@{} AndBlock:^(id data, NSError *error) {
        if (data) {
            self.hotArray = [data objectForKey:@"brands"];
            [self.tableView reloadData];
        }
    }];
    //所有品牌
    [[DHNetAPIClient shareDHNetAPIClient] request_brandsAndBlock:^(id data, NSError *error) {
        if (data) {
//            NSArray *arr = @[@{@"_id" : @"5ac32482ae65a692719037e6",
//                @"name": @"张朋",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"刘德华",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"@5ac32482ae65a692719037e6",
//                @"name": @"张学友",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"郭富城",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"郑玲璐",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"迪丽热巴",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"鹿晗",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"古巨基",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"匿名",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"anglebaby",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"五月天",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"SHE",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            },@{
//                @"_id": @"5ac32482ae65a692719037e6",
//                @"name": @"beyond",
//                @"logo": @"http://这是品牌logo.png",
//                @"cover": @"http://这是品牌logo背后的封面图.png"
//            }];
            self.brandArray = [self sortObjectsAccordingToInitialWith:[data objectForKey:@"brands"]];
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.brandArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return [self.brandArray[section - 1] count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CGFloat w = (kScreenWidth - 32) / 3;
        CGFloat h = w * 0.51;
        if (self.hotArray.count % 3 == 0) {
            return 87 + (self.hotArray.count / 3) * h;
        }else{
            return 87 + (self.hotArray.count / 3 + 1) * h;
        }
    }else{
        return 63;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        DHHomeHotBrandsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeHotBrandsCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.hotArray];
        cell.moreView.hidden = YES;
        return cell;
    }else{
        DHSubscription_BrandViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSubscription_BrandViewCell];
        NSArray *arr = self.brandArray[indexPath.section - 1];
        S2_Brand *model = arr[indexPath.row];
        cell.nameLabel.text = model.name;
        [cell.imgView dh_setImageURLString:model.logo];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section != 0) {
        NSArray *arr = self.brandArray[indexPath.section - 1];
        S2_Brand *model = arr[indexPath.row];
        DHS2_BrandViewController *brandController = [[DHS2_BrandViewController alloc] initWithBrandID:model._id];
        brandController.hidesBottomBarWhenPushed = YES;
        [self.viewController.navigationController pushViewController:brandController animated:YES];
    }
}

// 按首字母分组排序数组
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
    
    // 初始化UILocalizedIndexedCollation
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据，我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
    //初始化27个空数组加入newSectionsArray
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    //将每个名字分到某个section下
//    for (PersonModel *personModel in _contactsArr) {
//        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
//        NSInteger sectionNumber = [collation sectionForObject:personModel collationStringSelector:@selector(name)];
//        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
//        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
//        [sectionNames addObject:personModel];
//    }
    for (NSDictionary *dic in arr) {
        S2_Brand *model = [S2_Brand modelWithDictionary:dic];
        NSInteger sectionNumber = [collation sectionForObject:model collationStringSelector:@selector(name)];
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
        [sectionNames addObject:model];
    }
    
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
        newSectionsArray[index] = sortedPersonArrayForSection;
    }
    
    //删除空的数组
    NSMutableArray *finalArr = [NSMutableArray new];
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
            [finalArr addObject:newSectionsArray[index]];
        }
    }
    return finalArr;
}

@end
